/**
 * Project: complex.mina
 * 
 * File Created at 2011-3-16
 * $Id: Client.java 129 2011-03-18 03:43:37Z ymkyve501@163.com $
 * 
 * Copyright 1999-2100 Alibaba.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Alibaba Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Alibaba.com.
 */
package com.complex.mina;

import java.net.InetSocketAddress;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**
 * Client通过Server请求Provider的服务
 * 
 * @author gaoliang
 * @date 2011-3-16
 */
public class Client {
    public static void main(String[] args) throws Exception {
        try {
            //向server请求服务,server会将provider告诉client
            connect();

            Thread.sleep(3000);
            //向provider发送请求
            request();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void connect() {
        NioSocketConnector connector = new NioSocketConnector();
        connector.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new TextLineCodecFactory()));
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.setHandler(new ClientHandler());

        //连接到服务器
        ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 12345));
        future.awaitUninterruptibly(3000);
        IoSession session = future.getSession();
        //写入数据
        //请求连接服务:serviceName1:version1
        session.write("Client serviceName1:version1");
    }

    public static void request() {
        String service = (String) ClientHandler.message;
        NioSocketConnector connector = new NioSocketConnector();
        connector.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new TextLineCodecFactory()));
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.setHandler(new ClientHandler());

        //连接到服务器
        String[] strs = service.split(":");
        ConnectFuture future = connector.connect(new InetSocketAddress(strs[0], Integer
                .valueOf(strs[1])));
        future.awaitUninterruptibly(3000);
        IoSession session = future.getSession();
        session.write("Client");

        //通知monitor
        Monitor.log("Provider");
    }
}
